"""
Split configuration dialog - Simple synchronous version with settings persistence.
"""

import os
from typing import Optional, List, Dict, Any

from PyQt6.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QFormLayout,
    QLineEdit, QSpinBox, QDoubleSpinBox, QComboBox, QLabel, QPushButton,
    QTextEdit, QGroupBox, QRadioButton, QButtonGroup,
    QFileDialog, QMessageBox, QProgressBar, QDialogButtonBox,
    QCheckBox, QSlider, QListWidget, QListWidgetItem
)
from PyQt6.QtCore import Qt, pyqtSlot, QTimer
from PyQt6.QtGui import QFont

from ...core.pdf_processor import PDFProcessor
from ...core.pdf_splitter import PDFSplitter, SplitMode
from ...utils.settings_manager import get_settings_manager


class SimpleSplitDialog(QDialog):
    """Dialog for configuring PDF split operations - synchronous version."""

    def __init__(self, processor: PDFProcessor, splitter: PDFSplitter,
                 file_path: Optional[str], parent=None):
        super().__init__(parent)
        self.processor = processor
        self.splitter = splitter
        self.file_path = file_path
        self.settings_manager = get_settings_manager()

        self.init_ui()
        self.load_settings()

    def init_ui(self):
        """Initialize the user interface."""
        self.setWindowTitle("Split PDF")
        self.setMinimumSize(500, 600)
        self.resize(600, 700)

        # Main layout
        layout = QVBoxLayout(self)

        # Split mode selection
        mode_group = QGroupBox("Split Mode")
        mode_layout = QVBoxLayout(mode_group)

        self.mode_button_group = QButtonGroup(self)
        self.range_mode = QRadioButton("Split by Page Range")
        self.pages_mode = QRadioButton("Split by Fixed Page Count")
        self.bookmark_mode = QRadioButton("Split by Bookmarks")
        self.size_mode = QRadioButton("Split by File Size")

        self.mode_button_group.addButton(self.range_mode, 0)
        self.mode_button_group.addButton(self.pages_mode, 1)
        self.mode_button_group.addButton(self.bookmark_mode, 2)
        self.mode_button_group.addButton(self.size_mode, 3)

        mode_layout.addWidget(self.range_mode)
        mode_layout.addWidget(self.pages_mode)
        mode_layout.addWidget(self.bookmark_mode)
        mode_layout.addWidget(self.size_mode)

        # Range mode settings
        self.range_group = QGroupBox("Page Range Settings")
        range_layout = QFormLayout(self.range_group)

        self.range_input = QLineEdit()
        self.range_input.setPlaceholderText("e.g., 1-5, 10, 15-20")
        range_layout.addRow("Ranges:", self.range_input)

        # Pages mode settings
        self.pages_group = QGroupBox("Fixed Page Count Settings")
        pages_layout = QFormLayout(self.pages_group)

        self.pages_per_file = QSpinBox()
        self.pages_per_file.setMinimum(1)
        self.pages_per_file.setMaximum(999)
        self.pages_per_file.setValue(10)
        pages_layout.addRow("Pages per file:", self.pages_per_file)

        # Bookmark mode settings
        self.bookmark_group = QGroupBox("Bookmark Settings")
        bookmark_layout = QFormLayout(self.bookmark_group)

        self.bookmark_level = QSpinBox()
        self.bookmark_level.setMinimum(1)
        self.bookmark_level.setMaximum(10)
        self.bookmark_level.setValue(1)
        bookmark_layout.addRow("Level:", self.bookmark_level)

        # File size mode settings
        self.size_group = QGroupBox("File Size Settings")
        size_layout = QFormLayout(self.size_group)

        self.max_size_mb = QDoubleSpinBox()
        self.max_size_mb.setMinimum(0.1)
        self.max_size_mb.setMaximum(1000.0)
        self.max_size_mb.setValue(10.0)
        self.max_size_mb.setSuffix(" MB")
        self.max_size_mb.setDecimals(1)
        size_layout.addRow("Maximum file size:", self.max_size_mb)

        # Output settings
        output_group = QGroupBox("Output Settings")
        output_layout = QFormLayout(output_group)

        self.output_dir = QLineEdit()
        if self.file_path:
            self.output_dir.setText(os.path.dirname(self.file_path))
        output_layout.addRow("Output Directory:", self.output_dir)

        browse_btn = QPushButton("Browse...")
        browse_btn.clicked.connect(self.browse_output_dir)
        output_layout.addRow("", browse_btn)

        # Status label
        self.status_label = QLabel("")
        self.status_label.setWordWrap(True)
        output_layout.addRow("", self.status_label)

        # Additional output settings
        self.filename_template = QLineEdit("{original_name}_{part}")
        output_layout.addRow("Filename template:", self.filename_template)

        self.preserve_metadata = QCheckBox("Preserve metadata")
        self.preserve_metadata.setChecked(True)
        output_layout.addRow("", self.preserve_metadata)

        # Dialog buttons
        button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok |
            QDialogButtonBox.StandardButton.Cancel
        )
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        self.ok_button = button_box.button(QDialogButtonBox.StandardButton.Ok)
        self.ok_button.setText("Split")

        layout.addWidget(mode_group)
        layout.addWidget(self.range_group)
        layout.addWidget(self.pages_group)
        layout.addWidget(self.bookmark_group)
        layout.addWidget(self.size_group)
        layout.addWidget(output_group)
        layout.addWidget(button_box)

        # Setup connections
        self.mode_button_group.buttonClicked.connect(self.on_mode_changed)
        self.range_mode.setChecked(True)
        self.on_mode_changed()

    def load_settings(self):
        """Load saved settings into UI controls."""
        settings = self.settings_manager.get_settings()

        # Load split mode
        if 0 <= settings.split_mode <= 3:
            button = self.mode_button_group.button(settings.split_mode)
            if button:
                button.setChecked(True)
                # Trigger the mode change to show correct settings group
                self.on_mode_changed()

        # Load split parameters
        self.range_input.setText(settings.page_ranges)
        self.pages_per_file.setValue(settings.pages_per_file)
        self.bookmark_level.setValue(settings.bookmark_level)
        self.max_size_mb.setValue(settings.max_size_mb)

        # Load output settings
        if settings.output_directory and os.path.exists(settings.output_directory):
            self.output_dir.setText(settings.output_directory)
        else:
            # Use document directory as default
            if self.file_path:
                self.output_dir.setText(os.path.dirname(self.file_path))
                self.settings_manager.update_settings(output_directory=self.output_dir.text())

        self.filename_template.setText(settings.filename_template)
        self.preserve_metadata.setChecked(settings.preserve_metadata)

        # Load window geometry
        if settings.window_width > 0 and settings.window_height > 0:
            self.resize(settings.window_width, settings.window_height)

    def save_settings(self):
        """Save current UI settings."""
        settings = {
            'split_mode': self.mode_button_group.checkedId(),
            'page_ranges': self.range_input.text(),
            'pages_per_file': self.pages_per_file.value(),
            'bookmark_level': self.bookmark_level.value(),
            'max_size_mb': self.max_size_mb.value(),
            'output_directory': self.output_dir.text(),
            'filename_template': self.filename_template.text(),
            'preserve_metadata': self.preserve_metadata.isChecked(),
            'window_width': self.width(),
            'window_height': self.height()
        }

        self.settings_manager.update_settings(**settings)
        self.settings_manager.save_settings()

        # Add current file to recent files
        if self.file_path:
            self.settings_manager.add_recent_file(self.file_path)

    def on_mode_changed(self):
        """Handle split mode change."""
        mode = self.mode_button_group.checkedId()

        # Hide all groups
        self.range_group.setVisible(False)
        self.pages_group.setVisible(False)
        self.bookmark_group.setVisible(False)
        self.size_group.setVisible(False)

        # Show relevant group
        if mode == 0:  # Range mode
            self.range_group.setVisible(True)
        elif mode == 1:  # Pages mode
            self.pages_group.setVisible(True)
        elif mode == 2:  # Bookmark mode
            self.bookmark_group.setVisible(True)

            # Check if document has bookmarks
            outline = self.processor.get_outline()
            if not outline:
                self.bookmark_mode.setEnabled(False)
                self.bookmark_mode.setToolTip("Document has no bookmarks")
            else:
                self.bookmark_mode.setEnabled(True)
        elif mode == 3:  # Size mode
            self.size_group.setVisible(True)

    def browse_output_dir(self):
        """Browse for output directory."""
        dir_path = QFileDialog.getExistingDirectory(
            self,
            "Select Output Directory",
            self.output_dir.text() or os.path.expanduser("~")
        )
        if dir_path:
            self.output_dir.setText(dir_path)

    def validate_inputs(self) -> bool:
        """Validate input fields."""
        output_dir = self.output_dir.text().strip()
        if not output_dir:
            QMessageBox.warning(self, "Invalid Input", "Please specify an output directory.")
            return False

        if not os.path.exists(output_dir):
            QMessageBox.warning(self, "Invalid Input", "Output directory does not exist.")
            return False

        mode = self.mode_button_group.checkedId()
        if mode == 0:  # Range mode
            range_text = self.range_input.text().strip()
            if not range_text:
                QMessageBox.warning(self, "Invalid Input", "Please specify page ranges.")
                return False

        return True

    def accept(self):
        """Execute the split operation."""
        if not self.validate_inputs():
            return

        # Save current settings before splitting
        self.save_settings()

        # Disable buttons during operation
        self.ok_button.setEnabled(False)

        # Get parameters
        mode = self.mode_button_group.checkedId()
        output_dir = self.output_dir.text()

        try:
            # Execute split synchronously
            if mode == 0:  # Range mode
                ranges_text = self.range_input.text()
                ranges = self.splitter.parse_page_ranges(ranges_text, self.processor.get_page_count())
                self.status_label.setText("Splitting by page range...")
                results = self.splitter.split_by_range(ranges, output_dir)

            elif mode == 1:  # Pages mode
                pages_per_file = self.pages_per_file.value()
                self.status_label.setText(f"Splitting every {pages_per_file} pages...")
                results = self.splitter.split_by_pages(pages_per_file, output_dir)

            elif mode == 2:  # Bookmark mode
                level = self.bookmark_level.value()
                self.status_label.setText(f"Splitting by bookmarks (level {level})...")
                results = self.splitter.split_by_outline(output_dir, level)

            else:  # Size mode
                max_size_mb = self.max_size_mb.value()
                self.status_label.setText(f"Splitting by max size {max_size_mb} MB...")
                results = self.splitter.split_by_size(max_size_mb, output_dir)

            # Show results
            successful = sum(1 for r in results if r.success)
            total = len(results)

            if successful == total:
                QMessageBox.information(
                    self,
                    "Split Complete",
                    f"Successfully created {successful} files in:\n{output_dir}"
                )
                super().accept()  # Close dialog
            else:
                QMessageBox.warning(
                    self,
                    "Split Partially Complete",
                    f"Only {successful} out of {total} files were created successfully.\n"
                    "Check the output directory for details."
                )
                self.ok_button.setEnabled(True)

        except Exception as e:
            QMessageBox.critical(
                self,
                "Split Failed",
                f"Failed to split PDF:\n{str(e)}"
            )
            self.ok_button.setEnabled(True)

        self.status_label.setText("")

    def reject(self):
        """Handle dialog rejection."""
        # Save settings even if cancelled
        self.save_settings()
        super().reject()

    def closeEvent(self, event):
        """Handle dialog close event."""
        # Save settings when dialog is closed
        self.save_settings()
        super().closeEvent(event)